package com.xy.novelmanagement.controller;

import com.xy.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping("/")
public class IndexController {
		@RequestMapping("/index")
		public String toIndex(){
				return "/static/index";
		}

		@RequestMapping("/login")
		public void toLogin(HttpServletResponse response, HttpServletRequest request){
				try {
//						response.setContentType("text/html;charset=UTF-8");
//						response.sendRedirect("/wf-admin/index.html#/login?redirect=%2Findex");
						request.getRequestDispatcher("/wf-admin/index.html#/login?redirect=%2Findex").forward(request,response);
				} catch (Exception e) {
						e.printStackTrace();
				}
		}
		@RequestMapping("/test")
		public String test(){
				return "/index.html";
		}
		@RequestMapping("/getIndexData")
		@ResponseBody
		public Map<String,Object> getIndexData(){
				Map<String,Object> dataMap = new HashMap<>();
				Jedis jedis = JedisUtil.getConnect();
				String clickKey = "webClick";
				String downloadKey= "downloadClick";
				try {
						Map<String, String> clickMap =dataTransform( jedis.hgetAll(clickKey));
						Map<String, String> downloadMap = dataTransform( jedis.hgetAll(downloadKey));
						dataMap.put(clickKey,clickMap);
						dataMap.put(downloadKey,downloadMap);
				} catch (Exception e) {
						e.printStackTrace();
				} finally {
						JedisUtil.close(jedis);
				}

				return dataMap;
		}
		public Map<String,String> dataTransform(Map<String,String> src){
				Map<String,String> map = new HashMap<>();
				Calendar c =null;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int i=0;i<7;i++){
						c= Calendar.getInstance();
						c.add(Calendar.DAY_OF_MONTH, - i-1);//去过去七天的记录
						String data =sdf.format(c.getTime());
						String value = src.get(data);
						log.info("date="+data+"   value="+value);
						map.put("d"+(i+1),value);
				}
				return map;
		}
}
